package session;

import request.Dispatcher;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.io.IOException;

/**
 * 演示Session的作用。
 * 该Servlet用于处理用户的登陆请求，如果用户名密码正确，那么久转入到succ1中，并将登陆信息保存到Session中，否则返回登陆页面。
 */
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //校验验证码
        if (req.getParameter("vcText").equals("")||!req.getParameter("vcText").equals(req.getSession().getAttribute("vcText"))) {
            req.setAttribute("msg", "验证码错误！");
            RequestDispatcher dispatcher = req.getRequestDispatcher("/res/jsps/session/login.jsp");
            dispatcher.forward(req, resp);
        }

        String name = req.getParameter("name");
        String password = req.getParameter("password");
        if ("admin".equals(name) && "admin".equals(password)) {
            HttpSession session = req.getSession();
            session.setAttribute("user", "admin");
            RequestDispatcher dispatcher = req.getRequestDispatcher("/res/jsps/session/succ1.jsp");
            dispatcher.forward(req, resp);
        } else {
            req.setAttribute("msg", "登陆失败，用户名或者密码错误！");
            RequestDispatcher dispatcher = req.getRequestDispatcher("/res/jsps/session/login.jsp");
            dispatcher.forward(req, resp);
        }
    }
}
